package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.RedisConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.DishService;
import com.sky.vo.DishSelectIdVO;
import com.sky.vo.DishVO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {
    private static final Logger log = LoggerFactory.getLogger(DishServiceImpl.class);
    @Resource
    DishMapper dishMapper;
    @Resource
    DishFlavorMapper dishFlavorMapper;
    @Resource
    RedisTemplate redisTemplate;

    @Override
    public Result<PageResult> selectPageCategory(DishPageQueryDTO dto) {
        Page<DishVO> dishes = dishMapper.selectPageCategory(dto);
        PageHelper.startPage(dishes.getPages(), dishes.getPageSize());
        PageResult build = PageResult.builder().total(dishes.getTotal()).records(dishes.getResult()).build();
        return Result.success(build);
    }

    @Override
    public List<DishSelectIdVO> selectId(Integer categoryId) {
        List<DishSelectIdVO> dishes = dishMapper.selectId(categoryId);
        return dishes;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertDish(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        int i = dishMapper.insertDish(dish);

        log.info("新增的菜品id:{}", dish.getId());
        // 对口味表进行操作
        List<DishFlavor> flavors = dto.getFlavors();
        if (CollectionUtils.isNotEmpty(flavors)) {
            flavors.stream().forEach(t -> {
                t.setDishId(dish.getId());
            });
        }
        int a = dishFlavorMapper.insertDishFlavor(flavors);

        //进行删除缓存
        try{
            cleanCache(RedisConstant.DISH_PAGE+dto.getCategoryId());
        }catch (Exception e){
            e.printStackTrace();
        }

        log.info("新增的口味数据:{}", a);
        return i;
    }

    @Override
    public DishVO selectDishAll(Long id) {
        DishVO dishVO = dishMapper.selectByIdDishAll(id);
        log.info("查询出来的结果------{}", dishVO);
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);
        log.info("查出来的口味{}", flavors);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateDishAll(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        int i = dishMapper.updateDishAll(dish);
        log.info("修改的菜品信息{}", i);
        //删除口味表
        dishFlavorMapper.deletByDishId(List.of(dish.getId()));
        //在进行新增
        List<DishFlavor> flavors = dto.getFlavors();
        flavors.stream().forEach(t -> {
            t.setDishId(dish.getId());
        });
         dishFlavorMapper.insertDishFlavor(flavors);

        //进行删除缓存
        try{
            //这里加"*" 是因为可能会修改菜品套餐的分类 进行通配符删除
            cleanCache(RedisConstant.DISH_PAGE+"*");
        }catch (Exception e){
            e.printStackTrace();
        }
        return i;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deletByIdDishAll(List<Long> ids) {
        int i = dishMapper.deletByIdDishAll(ids);
        //删除口味
        dishFlavorMapper.deletByDishId(ids);

        try{
            //这里加"*" 是因为可能会修改菜品套餐的分类 进行通配符删除
            cleanCache(RedisConstant.DISH_PAGE+"*");
        }catch (Exception e){
            e.printStackTrace();
        }
        return i;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        // 将小程序菜品中的数据放到缓存中
        List<DishVO> dishVOList =new ArrayList<>();
        try {
            dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(RedisConstant.DISH_PAGE + dish.getCategoryId());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (CollectionUtils.isNotEmpty(dishVOList)) {
            log.warn("从缓存中获取数据 {}",dishVOList);
           return dishVOList;
        }
        List<Dish> dishList = dishMapper.selectByCategoryId(dish.getCategoryId());
        log.info("从数据库中查询到的数据{}",dishList);
        dishVOList = dishList.stream().map(list -> {
            DishVO dishVO = new DishVO();
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectByDishId(list.getId());
            BeanUtils.copyProperties(list, dishVO);
            dishVO.setFlavors(dishFlavors);
            return dishVO;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(RedisConstant.DISH_PAGE+dish.getCategoryId(),dishVOList,1, TimeUnit.DAYS);
        log.warn("---从数据库中获取");
        return dishVOList;
    }

    private Long cleanCache(String pattern){
        //查询全部
        Set keys = redisTemplate.keys(pattern);
        //进行删除
        Long booleandelete = redisTemplate.delete(keys);
        log.warn("小程序删除的数据:{}",booleandelete);
        return booleandelete;
    }
}
